<script setup>
import { artGetChannelsService, artDelChannelService } from '@/api/article'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ref } from 'vue'
import ArticleEdit from './ArticleEdit.vue'

const channelList = ref()
// 添加一个提高用户体验的效果，在请求之前添加一个缓冲的动效，数据请求完成，效果消失
const loading = ref(false)
const getChannelList = async () => {
  loading.value = true
  const res = await artGetChannelsService()
  channelList.value = res.data.data
  loading.value = false
  console.log(channelList.value)
}
getChannelList()
const dialog = ref()
//点击添加按钮给弹窗传递数据
const onAddChannel = () => {
  // 如果是添加，就传一个空数据
  dialog.value.open({})
}
// 点击编辑给弹窗组件传递数据
const onEnditChannel = (row, $index) => {
  //TODO:点击编辑分类的方法
  dialog.value.open(row, $index)
}
// 点击删除传递该条数据
// TODO:点击删除分类的方法
const onDeleteChannel = (row) => {
  ElMessageBox.confirm('确定要删除该条分类码?', '提醒：', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await artDelChannelService(row.id)
      console.log(res)
      getChannelList()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 子组件操作之后，进行重新刷新页面
const onSuccess = () => {
  getChannelList()
}
</script>

<template>
  <page-container title="文章分类">
    <template #extra>
      <el-button type="primary" @click="onAddChannel">添加分类</el-button>
    </template>
    <el-table :data="channelList">
      <el-table-column label="序号" type="index" width="150"></el-table-column>
      <el-table-column label="分类名称" prop="cate_name"></el-table-column>
      <el-table-column label="分类别名" prop="cate_alias"></el-table-column>
      <el-table-column label="操作" width="100">
        <!-- row就是channelList的一项，$index是下标 -->
        <template #default="{ row, $index }">
          <el-button
            type="primary"
            plain
            :icon="Edit"
            circle
            @click="onEnditChannel(row, $index)"
          ></el-button>
          <el-button
            type="danger"
            plain
            :icon="Delete"
            circle
            @click="onDeleteChannel(row, $index)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <!-- 当数组中没有数据的时候 -->
        <el-empty description="还没有分类"></el-empty>
      </template>
    </el-table>
    <!-- 弹窗 -->
    <ArticleEdit ref="dialog" @success="onSuccess"></ArticleEdit>
  </page-container>
</template>
<style lang="scss" scoped></style>
